import json
from django.utils.decorators import method_decorator
from .models import UserInfo, rolename, rolemenus, router
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from django.views import View

from .roles import rolesoperate


class usersoperate(View):

    def adminConfirm(self,currentuser):
        # print(currentuser)
        user_info = UserInfo.objects.get(cardid=currentuser)
        permission = user_info.permission
        login = user_info.login
        if permission != '管理员':
            return False
        elif login != True:
            return False
        else:
            return True

    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        action = kwargs.pop('action', None)
        if action == 'usersadd':
            return self.usersadd(request, *args, **kwargs)
        elif action == 'usersdel':
            return self.usersdel(request, *args, **kwargs)
        elif action == 'showuserEdit':
            return self.showuserEdit(request, *args, **kwargs)
        elif action == 'usersedit':
            return self.usersedit(request, *args, **kwargs)
        elif action == 'editUserlogin':
            return self.editUserlogin(request, *args, **kwargs)
        elif action == 'users':
            return self.users(request, *args, **kwargs)
        elif action == 'flush':
            return self.flush(request, *args, **kwargs)
        else:
            return super().dispatch(request, *args, **kwargs)

    @csrf_exempt
    def usersadd(self,request, *args, **kwargs):
        users = UserInfo.objects.values('username','cardid')
        data = json.loads(request.body)
        # print(data)
        secret_key="1111"
        username = data.get('username')
        cardid = data.get('cardid')
        # print(list(users))
        for user in list(users):
            if user['username'] == username or user['cardid'] == cardid:
                return JsonResponse({'status': '400'},status=400)
        phonenumber = data.get('mobile')
        email = data.get('email')
        # 获取前端发送的用户名
        data = {
            'username': username,
            'phonenumber': phonenumber,
            "secret_key" : secret_key,
            "permission": "用户",
            'email': email,
            "login" : True,
            'cardid': cardid
        }
        UserInfo.objects.create(**data)
        return JsonResponse({'message': '添加成功'})

    @csrf_exempt
    def usersdel(self,request, *args, **kwargs):
        data = json.loads(request.body)
        cardid = data.get('cardid')
        UserInfo.objects.filter(cardid=cardid).delete()
        return JsonResponse({'message': '删除成功'})

    @csrf_exempt
    def showuserEdit(self, request, *args, **kwargs):
        data = json.loads(request.body)
        cardid = data.get('cardid')
        user_info = UserInfo.objects.get(cardid=cardid)
        phonenumber = user_info.phonenumber
        username = user_info.username
        email = user_info.email
        return JsonResponse({'phonenumber': phonenumber,'username':username,'cardid':cardid,'email':email})

    @csrf_exempt
    def usersedit(self, request, *args, **kwargs):
        data = json.loads(request.body)
        cardid = data.get('cardid')
        phonenumber = data.get('phonenumber')
        email = data.get('email')
        date1 = {
            'email': email,
            "phonenumber": phonenumber
        }
        UserInfo.objects.filter(cardid=cardid).update(**date1)
        return JsonResponse({'message': '修改成功'})

    @csrf_exempt
    def editUserlogin(self, request, *args, **kwargs):
        data = json.loads(request.body)
        cardid = data.get('cardid')
        user_info = UserInfo.objects.get(cardid=cardid)
        login = user_info.login
        if login == True:
            permission = False
        else:
            permission = True
        date1 = {
            "login": permission
        }
        UserInfo.objects.filter(cardid=cardid).update(**date1)
        return JsonResponse({'message': '修改成功'},status=200)


    def users(self,request, *args, **kwargs):
        data = json.loads(request.body)
        pagenum = data.get('pagenum')-1
        pagesize = data.get('pagesize')
        query = data.get('query')
        users = UserInfo.objects.values('cardid','email', 'username', 'phonenumber', 'permission', 'login')
        users = list(users)
        users = sorted(users, key=lambda x: x['permission'] == '管理员', reverse=True)
        if query != "":
            users = [user for user in users if query in user['username']]#按照前端模糊查找信息时返回的列表
        user = [users[i:i + pagesize] for i in range(0, len(users), pagesize)]
        if user == []:
            return JsonResponse({'message': '没有这个用户！'},status=201)
        rolegrade = list(rolename.objects.values('role','grade'))
        sorted_data = sorted(user[pagenum],key=lambda x: next(item['grade'] for item in rolegrade if item['role'] == x['permission']))
        data = {
            "results": sorted_data,
            "total": len(users),
        }
        return JsonResponse(data, safe=False,status=200)

    def flush(self,request, *args, **kwargs):
        data = json.loads(request.body)
        cardid = data.get('cardid')
        if cardid == None:
            return JsonResponse({}, status=201)
        user_info = UserInfo.objects.get(cardid=cardid)
        permission = user_info.permission
        role_menus = rolemenus.objects.filter(role=permission)
        menu = []
        for i in role_menus:
                menu.append(i.id)
        #只拿是页面的菜单id
        menus = rolesoperate.getmenus1(self, permission=permission)
        menus = rolesoperate.remove_empty_children(self,menus)
        menus = rolesoperate.get_ids_without_children(self,menus)
        # 查询 id 列在 id_list 中的行数据
        queryset = router.objects.filter(id__in=menu)
        # 遍历查询结果并输出每一行的 name、component 和 path 列数据
        path = []
        for row in queryset:
            path.append({'name':row.name, 'component':row.component, 'path':row.path})
        login = user_info.login
        cardid = user_info.cardid
        return JsonResponse({"permission":permission,"login":login,'cardid':cardid,'path':path,'menus':menus}, safe=False)


import io
import json
from django.views.decorators.csrf import csrf_exempt
from myapp.models import UserInput
from django.http import HttpRequest, HttpResponse, JsonResponse
from rest_framework.views import APIView
from django.http import HttpResponse
from reportlab.lib.pagesizes import letter
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, PageBreak
from reportlab.lib.styles import getSampleStyleSheet


class polls_views(APIView):

    def export_pdf(request):
        response = HttpResponse(content_type='application/pdf')
        # response['Content-Disposition'] = 'inline; filename="your_report.pdf"'
        buffer = io.BytesIO()
        doc = SimpleDocTemplate(buffer, pagesize=letter)
        data = UserInput.objects.all()
        elements = []
        styles = getSampleStyleSheet()
        max_pages = 5
        max_lines_per_page = 10
        current_page = 1
        current_line = 0
        pdfmetrics.registerFont(TTFont('simsun', 'D:\Tencent_IM_8_zby\myproject\myapp\SourceHanSerifCN-Regular.ttf'))
        for item in data:
            if current_page > max_pages:
                break
            if current_line >= max_lines_per_page:
                elements.append(PageBreak())  # Add a page break
                doc.build(elements)  # 创建新页面
                elements = []  # 重置元素列表
                current_line = 0
            problem = item.problem
            answer = item.answer
            # 创建自定义样式以控制文本布局
            custom_style = styles['Normal'].clone(None)
            custom_style.fontName = 'simsun'
            custom_style.wordWrap = 'CJK'
            custom_style.leading = 30  # 设置行高等于字体大小
            if item.Similarity_problem is not None:
                Similarity_problem = item.Similarity_problem
                # 设置字体大小
                custom_style.fontSize = 18
                elements.append(Paragraph(problem, custom_style))
                elements.append(Spacer(1, 1))  # Add some space between sections
                # 设置字体大小
                custom_style.fontSize = 12
                elements.append(Paragraph(answer, custom_style))
                elements.append(Spacer(1, 3))  # Add some space between sections
                # 设置字体大小
                custom_style.fontSize = 18
                elements.append(Paragraph(Similarity_problem, custom_style))
                elements.append(Spacer(1, 1))  # Add some space between sections
                # 设置字体大小
                custom_style.fontSize = 12
                elements.append(Paragraph(answer, custom_style))
                elements.append(Spacer(1, 3))  # Add some space between sections
            else:
                # 设置字体大小
                custom_style.fontSize = 18
                custom_style.leading = 30  # 设置行高等于字体大小
                elements.append(Paragraph(problem, custom_style))
                elements.append(Spacer(1, 1))  # Add some space between sections
                # 设置字体大小
                custom_style.fontSize = 12
                custom_style.leading = 30  # 设置行高等于字体大小
                elements.append(Paragraph(answer, custom_style))
                elements.append(Spacer(1, 3))  # Add some space between sections

            current_line += 1

        doc.build(elements)  # 最后一页可能不满，这里再次构建以确保保存

        pdf = buffer.getvalue()
        buffer.close()
        response.write(pdf)
        return response

    @csrf_exempt
    def add(request, *args, **kwargs):
        data = json.loads(request.body)
        type = data.get('type')
        problem = data.get('problem')
        Similarity_problem = data.get('Similarity_problem')
        answer = data.get('answer')
        # 获取前端发送的用户名
        data = {
            'type': type,
            'problem': problem,
            'Similarity_problem': Similarity_problem,
            "answer": answer
        }
        UserInput.objects.create(**data)
        return JsonResponse({'message': '添加成功'})

    # 自定义排序函数，按照type字段排序
    def custom_sort(item):
        return item['type']

    @csrf_exempt
    def opstion(request, *args, **kwargs):
        data = UserInput.objects.values('type', 'problem', 'Similarity_problem', 'answer')
        data = list(data)
        # 使用sorted函数排序
        sorted_data = sorted(data, key=polls_views.custom_sort)
        data = {
            "results": sorted_data,
        }
        return JsonResponse(data, safe=False, status=200)



